/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bilibili.draweetext.demo.itemprovider;

import static com.bilibili.draweetext.demo.util.Constants.HEIGHT;
import static com.bilibili.draweetext.demo.util.Constants.INT_3;
import static com.bilibili.draweetext.demo.util.Constants.WIDTH;

import com.bilibili.draweetext.DraweeSpan;
import com.bilibili.draweetext.DraweeTextView;
import com.bilibili.draweetext.demo.ResourceTable;
import com.bilibili.draweetext.demo.util.ResUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.RecycleItemProvider;
import ohos.agp.components.element.PixelMapElement;

import java.util.ArrayList;

/**
 * It helps to populate the recycle items
 */
public class RecycleProvider extends RecycleItemProvider {
    private AbilitySlice slice;

    private ArrayList<String> sequences;

    public RecycleProvider(AbilitySlice mainSlice, ArrayList<String> listItems) {
        slice = mainSlice;
        sequences = listItems;
    }

    @Override
    public int getCount() {
        return sequences.size() * INT_3;
    }

    @Override
    public Object getItem(int position) {
        return "";
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        return getRootView(position);
    }

    private Component getRootView(int position) {
        Component rootView = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_row_item, null, false);

        PixelMapElement pixelMapElement = ResUtil.getPixelMapDrawable(slice, ResourceTable.Media_icon);
        DraweeSpan span = new DraweeSpan.Builder(sequences.get(position % sequences.size())).setLayout(WIDTH, HEIGHT)
            .setPlaceHolderImage(pixelMapElement)
            .build();

        DraweeTextView text;
        Component component = rootView.findComponentById(ResourceTable.Id_drawee_text);
        if (component instanceof DraweeTextView) {
            text = (DraweeTextView) component;
            text.setText("~~~~~~~~~~~~~~~~~Hello World~~~~~~~~~~~~~~~~~");
            text.setAroundElements(span, null, span, null);
        }
        return rootView;
    }
}

